﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

using TravelSite.DAL;
using TravelSite.DAL.Repositories;
using TravelSite.Entities;
using TravelSite.Code;

namespace TravelSite.Admin
{
    public partial class ContractTemplate : BaseDataPage
    {
        public string ConditionalJS;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                LoadData();

            if (!IsIE())
            {
                fuContractTemplate.Style.Add("display", "none");
                fuContractTemplate.Attributes.Add("onchange", "$('#btnSaveContractTemplate').click()");

                fuEmailTemplate.Style.Add("display", "none");
                fuEmailTemplate.Attributes.Add("onchange", "$('#btnSaveEmailTemplate').click()");
            }
            else
            {
                fuContractTemplate.Style.Add("margin-bottom", "5px;");
                fuEmailTemplate.Style.Add("margin-bottom", "5px;");

                ConditionalJS = "$('#lbSaveEmailTemplate').show(); $('#fuEmailTemplate').show();";
            }
        }

        public override void LoadData()
        {
            using (var repo = RepositoryFactory.ResolveRepository<TemplateRepository>())
            {
                rptFiles.DataSource = repo.FindAll();
                rptFiles.DataBind();
            }
        }

        protected void rptFiles_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Template rowView = e.Item.DataItem as Template;

                var hlLink = e.Item.FindControl("hlLink") as HyperLink;
                hlLink.NavigateUrl = "~/Files/Templates/" + rowView.FileName;
                //hlLink.Text = rowView.FileName;

                var delBtn = e.Item.FindControl("btnDeleteFile") as ImageButton;
                delBtn.Visible = rowView.AllowDelete;
                delBtn.OnClientClick = string.Format("return confirm('Are you sure you want to delete file\\n{0}?');", rowView.FileName);
                delBtn.CommandArgument = rowView.TemplateId.ToString();

                var img = e.Item.FindControl("imgIsEmail") as Image;
                if (rowView.IsEmail)
                {
                    img.ImageUrl = "~/images/design/email_icon.png";
                    hdEmailExists.Value = "1";
                }
                else
                    img.ImageUrl = "~/images/design/office_word_icon.png";
            }
        }

        protected void rptFiles_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument);
            if (e.CommandName == "DeleteFile")
            {
                using (var repo = RepositoryFactory.ResolveRepository<TemplateRepository>())
                {
                    Template temp = repo.Find(id);
                    string fileName = temp.FileName;

                    string result = repo.Delete(id);
                    if (!string.IsNullOrEmpty(result))
                    {
                        JsCodeToRunOnReady += string.Format("alert('{0}');", result);
                        return;
                    }
                    else
                    {
                        try
                        {
                            File.Delete(Path.Combine(MapPath("~/Files/Templates/"), fileName));
                            LoadData();

                            if (temp.IsEmail)
                                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowLink", string.Format("$('#hlEmailTemplate').show(); {0}", ConditionalJS), true);
                                hdEmailExists.Value = "0";
                        }
                        catch{}
                    }
                }
            }
        }

        protected void btnSaveContractTemplate_Click(object sender, EventArgs e)
        {
            if (!fuContractTemplate.HasFile)
                return;

            using (var repo = RepositoryFactory.ResolveRepository<TemplateRepository>())
            {
                Template item = repo.Find(Path.GetFileName(fuContractTemplate.FileName));
                if (item != null)
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "alert('Such File Name already exists!');", true);
                    return;
                }
            }
            
            string filePath = Path.Combine(Server.MapPath("~/Files/Templates"), fuContractTemplate.FileName);
            fuContractTemplate.SaveAs(filePath);
                        
            //string fields = WordInterop.DocumentFields(filePath);
            string fields = WordInterop.DocumentPlaceHolders(filePath);

            if (string.IsNullOrEmpty(fields))
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "alert('No field in file detected or file is not ms word document!');", true);
                return;
            }

            using (var repo = RepositoryFactory.ResolveRepository<TemplateRepository>())
            {
                Template temp = new Template();
                temp.FileName = fuContractTemplate.FileName;
                temp.IsEmail = false;
                repo.Insert(temp, fields);
            }
            LoadData();
        }

        protected void btnSaveEmailTemplate_Click(object sender, EventArgs e)
        {
            if (!fuEmailTemplate.HasFile)
                return;

            if (Path.GetExtension(fuEmailTemplate.FileName).ToLower() != ".txt")
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "alert('Email template must be in txt format!');", true);
                return;
            }

            fuEmailTemplate.SaveAs(Path.Combine(Server.MapPath("~/Files/Templates"), fuEmailTemplate.FileName));
            using (var repo = RepositoryFactory.ResolveRepository<TemplateRepository>())
            {
                Template temp = new Template();
                temp.FileName = fuEmailTemplate.FileName;
                temp.IsEmail = true;
                repo.Insert(temp, null);
            }
            LoadData();
        }

        
    }
}